package com.cesce.batch.cobros.items;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.batch.item.file.transform.FieldExtractor;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;


public class BeanWrapperFieldExtractorDateFormatting<T> implements FieldExtractor<T> {

	private String[] names;
	
	private Map<String, String> dateFormatting;
	
	/**
	 * @param names field names to be extracted by the {@link #extract(Object)} method.
	 */
	public void setNames(final String[] names) {
	    this.names = names;
	}
	
	/**
	 * @param dateFormatting the dateFormatting to set
	 */
	public void setDateFormatting(final Map<String, String> dateFormatting) {
	    this.dateFormatting = dateFormatting;
	}
	

	public Object[] extract(final T item) {
	    final List<Object> values = new ArrayList<Object>();
	
	    final BeanWrapper bw = new BeanWrapperImpl(item);
	    for (final String propertyName : this.names) {
	        Object propertyValue = bw.getPropertyValue(propertyName);
	        if (propertyValue != null) {
	            final String myFormat = dateFormatting.get(propertyName);
	            // Do we have a format
	            if (myFormat != null) {
	                // only format Date and Calendar Objects
	                if (propertyValue instanceof Date) {
	                    propertyValue = DateFormatUtils.format((Date) propertyValue, myFormat);
	                } else if (propertyValue instanceof Calendar) {
	                    propertyValue = DateFormatUtils.format(((Calendar) propertyValue).getTime(), myFormat);
	                }
	            }
	        }
	        values.add(propertyValue);
	    }
	    return values.toArray();
	}
}